package com.lzh.o2o.web.shopadmin;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzh.o2o.dto.ImageHolder;
import com.lzh.o2o.dto.ShopExecution;
import com.lzh.o2o.enums.ShopStateEnum;
import com.lzh.o2o.exception.ShopOperationException;
import com.lzh.o2o.pojo.Area;
import com.lzh.o2o.pojo.PersonInfo;
import com.lzh.o2o.pojo.Shop;
import com.lzh.o2o.pojo.ShopCategory;
import com.lzh.o2o.service.AreaService;
import com.lzh.o2o.service.ShopCategoryService;
import com.lzh.o2o.service.ShopService;
import com.lzh.o2o.util.CodeUtil;
import com.lzh.o2o.util.HttpServletRequestUtil;
import com.lzh.o2o.util.ImageUtil;
import com.lzh.o2o.util.PathUtil;
import com.lzh.o2o.web.superadmin.AreaController;

/**
 * 
 * @ClassName: ShopManagementController
 * @Description: 管理店铺注册的逻辑
 * @author: haohao
 * @date: 2018年9月9日 下午9:59:24
 */
@Controller
@RequestMapping("/shopadmin")
public class ShopManagementController {
	@Autowired
	private ShopService shopService;
	@Autowired
	private ShopCategoryService shopCategoryService;
	@Autowired
	private AreaService areaService;
	Logger logger=LoggerFactory.getLogger(ShopManagementController.class);

	@RequestMapping(value = "/getshopmanagementinfo", method = RequestMethod.GET)
	@ResponseBody
	//判断是否是违规操作，没有经过登录就访问就直接重定向到店铺管理页面
	private Map<String,Object>getShopManagementInfo(HttpServletRequest request){
		logger.info("getShopManagementInfo方法开始");
		Map<String, Object> modelMap = new HashMap<String, Object>();
		//判断是否页面带了shopId参数
		logger.debug("店铺管理页面");
		long shopId = HttpServletRequestUtil.getLong(request, "shopId");
		if(shopId <= 0){
			logger.debug("没有携带Id");
			//没有携带，就是为登录状态，就尝试在Session中获取
			Object currentShopObj = request.getSession().getAttribute("currentShop");
			//如果没有，重定向到前段展示页面
			if(currentShopObj == null){
				logger.debug("session里面无法获取currentShop(操作店铺)的值,重定向到店铺列表");
				modelMap.put("redirect", true);
				modelMap.put("url","/o2o/shopadmin/shoplist");
			}else{
				logger.debug("之前有登陆过,可以直接访问");
				//如果之前有登录这系统，就说明有权限访问这系统
				Shop currentShop = (Shop)currentShopObj;
				modelMap.put("redirect", false);
				modelMap.put("shopId", currentShop.getShopId());
			}
			//页面携带了参数
		}else{
			logger.debug("访问的时候带有店铺Id");
			//如果携带了shopId，就说明有权限对用户进行操作
			Shop currentShop = new Shop();
			currentShop.setShopId(shopId);
			
			request.getSession().setAttribute("currentShop", currentShop);
			modelMap.put("redirect", false);
		}
		logger.info("返回是否需要重定向链接");
		return modelMap;
	}
	
	// 获取店铺列表
	@RequestMapping(value = "/getshoplist", method = RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> getShopList(HttpServletRequest request) throws ShopOperationException {
		logger.info("获取用户的商品列表");
		Map<String, Object> modelMap = new HashMap<String, Object>();
		// 确保是有当前用户
		PersonInfo user = new PersonInfo();
		user.setUserId(1l);
		user.setName("test");
		request.getSession().setAttribute("user", user);
		//从用户登录的Session中取出用户信息
		user = (PersonInfo) request.getSession().getAttribute("user");
		try {
			Shop shopCondition = new Shop();
			shopCondition.setOwner(user);
			//调用service层方法获取当前用户所对应的商铺
			logger.debug("按条件查找用户的商铺列表,如果没条件则查出全部列表");
			ShopExecution se = shopService.getShopList(shopCondition, 0, 100);
			modelMap.put("shopList", se.getShopList());
			modelMap.put("user", user);
			modelMap.put("success", true);
		} catch (Exception e) {
			logger.error("查询用户商铺列表失败");
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
		}
		logger.info("返回用户拥有的商铺列表");
		return modelMap;

	}

	// 获取店铺的信息
	@RequestMapping(value = "/getshopbyid", method = RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> getShopById(HttpServletRequest request) throws ShopOperationException, Exception {
		logger.info("按商铺Id查询商铺列表");
		Map<String, Object> modelMap = new HashMap<String, Object>();
		Long shopId = HttpServletRequestUtil.getLong(request, "shopId");
		if (shopId > -1) {
			try {
				logger.debug("调用service层寻找商铺列表");
				// 获取的为店铺列表信息
				Shop shop = shopService.getByShopId(shopId);
				// 获取区域列表信息
				logger.debug("调用service获取地域列表");
				List<Area> areaList = areaService.getAreaList();
				modelMap.put("shop", shop);
				modelMap.put("areaList", areaList);
				modelMap.put("success", true);
			} catch (Exception e) {
				logger.error("寻找商铺列表或者获取地域列表失败");
				// 如果报错，直接返回
				modelMap.put("success", false);
				modelMap.put("errMsg", e.toString());
			}
		} else {
			// 商品Id信息为空
			logger.error("没有获得商铺Id进行查询");
			modelMap.put("success", false);
			modelMap.put("errMsg", "empty shopId");
		}
		logger.info("返回按商铺Id查询的商铺信息");
		return modelMap;
	}

	@RequestMapping(value = "/getshopinitinfo", method = RequestMethod.GET)
	@ResponseBody
	// 获取店铺类别与区域信息，返回前段页面下拉列表展示
	private Map<String, Object> getShopInitInfo() {
		logger.info("获取店铺类别与区域信息方法开始");
		Map<String, Object> modelMap = new HashMap<String, Object>();
		List<ShopCategory> shopCategoryList = new ArrayList<ShopCategory>();
		List<Area> areaList = new ArrayList<Area>();
		try {
			logger.debug("获取商铺类别列表");
			shopCategoryList = shopCategoryService.getShopCategoryList(new ShopCategory());
			logger.debug("获取区域列表");
			areaList = areaService.getAreaList();
			modelMap.put("shopCategoryList", shopCategoryList);
			modelMap.put("areaList", areaList);
			modelMap.put("success", true);

		} catch (Exception e) {
			logger.error("获取商铺类别列表或区域列表失败");
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());

		}
		logger.info("获取商铺类别与区域类别供下拉列表显示");
		return modelMap;

	}

	@RequestMapping(value = "/registershop", method = RequestMethod.POST)
	@ResponseBody
	private Map<String, Object> registerShop(HttpServletRequest request) {
		logger.info("注册商铺");
		Map<String, Object> modelMap = new HashMap<String, Object>();
		// 调用验证码验证工具类,查询验证码是否正确
		if (!CodeUtil.checkVerifyCode(request)) {
			logger.error("输入的验证码错误");
			modelMap.put("success", false);
			modelMap.put("errMsg", "验证码输入错误");
			return modelMap;
		}

		// 1、接受并转化相应的参数，包括店铺信息以及图片信息
		String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
		// 1.1转换成json数据，先创建一个ObjectMapper
		ObjectMapper mapper = new ObjectMapper();
		// 定义一个pojo去接收，可以看github json文档
		Shop shop = null;
		try {
			logger.debug("将前端的JSON数据转换成Shop对象");
			shop = mapper.readValue(shopStr, Shop.class);
		} catch (Exception e) {
			logger.error("前端的JSON数据转换失败");
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
			logger.error("返回错误提示信息");
			return modelMap;
		}
		// 解析处理上传图片
		CommonsMultipartFile shopImg = null;
		// 参数意思为:从本次会话中获取上下文相关的内容
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (commonsMultipartResolver.isMultipart(request)) {
			logger.debug("获取图片流");
			// 强制转换，可以从multipartHttpResolverRequest获取文件流
			MultipartHttpServletRequest multipartHttpResolverRequest = (MultipartHttpServletRequest) request;
			// shopImg为前段定义的id
			shopImg = (CommonsMultipartFile) multipartHttpResolverRequest.getFile("shopImg");
		} else {
			logger.error("注册店铺的时候未上传图片");
			modelMap.put("success", false);
			modelMap.put("errMsg", "上传图片不能为空");
			return modelMap;
		}
		// 2、注册店铺
		if (shop != null && shopImg != null) {
			// 用户打开浏览器就是一次会话，可以将用户信息储存到Session中，再获取用户信息储存到店铺中，
			// 用户登录之后，会保存一个user的session
			logger.debug("是属于哪个用户创建的店铺");
			PersonInfo owner = (PersonInfo) request.getSession().getAttribute("user");
			// Session TODO
			shop.setOwner(owner);
			/*
			 * File shopImgFile =new
			 * File(PathUtil.getImgBasePath()+ImageUtil.getRandomFile()); try{
			 * shopImgFile.createNewFile(); }catch(Exception e){
			 * modelMap.put("success", false);
			 * modelMap.put("errMsg",e.getMessage()); return modelMap; }
			 */
			/*
			 * try{ //CommonsMultipartFile源码里面有个获取输入流的方法,输入流可以去转换成文件流
			 * inputStreamToFile(shopImg.getInputStream(),shopImgFile);
			 * 
			 * }catch(IOException e){ modelMap.put("success", false);
			 * modelMap.put("errMsg",e.getMessage()); return modelMap; }
			 */
			// 直接调用Service层的时候，传入shopImg.getInputStream
			ShopExecution se;
			try {
				//9-17，将图片流与图片名称封装成一个对象。重构第二次
				ImageHolder imageHolder = new ImageHolder(shopImg.getOriginalFilename(),shopImg.getInputStream());
				logger.debug("增加用户所拥有的店铺");
				se = shopService.addShop(shop,imageHolder );
				if (se.getState() == ShopStateEnum.CHECK.getState()) {
					modelMap.put("success", true);
					// 一个用户可以操作多个店铺，即一对多的关系
					@SuppressWarnings("unchecked")
					List<Shop> shopList = (List<Shop>) request.getSession().getAttribute("shopList");
					// 如果用户之前没有创建店铺,就把他新创建一个List来存放店铺
					if (shopList == null || shopList.size() == 0) {
						logger.debug("用户第一次注册店铺");
						shopList = new ArrayList<Shop>();
					}
					// 如果之前有店铺，即添加一个可以操作的店铺
					logger.debug("用户之前已有店铺");
					shopList.add(se.getShop());
					request.getSession().setAttribute("shopList", shopList);

				} else {
					logger.debug("用户创建店铺违规");				
					modelMap.put("success", false);
					modelMap.put("errMsg", se.getStateInfo());
				}
			} catch (ShopOperationException e) {
				logger.error("用户创建店铺操作异常");
				modelMap.put("success", false);
				modelMap.put("errMsg", e.getMessage());
			} catch (IOException e) {
				logger.error("用户上传图片解析异常");
				modelMap.put("success", false);
				modelMap.put("errMsg", e.getMessage());
			}
			// 如果创建成果，即是待审核状态
			logger.info("");
			return modelMap;
		} else {
			logger.error("没有输入完整的店铺信息");
			modelMap.put("success", false);
			modelMap.put("errMsg", "请输入店铺信息");
			return modelMap;
		}
		// 3、返回结果

	}

	@RequestMapping(value = "/modifyshop", method = RequestMethod.POST)
	@ResponseBody
	private Map<String, Object> modifyshop(HttpServletRequest request) {
		logger.info("修改店铺信息开始");
		Map<String, Object> modelMap = new HashMap<String, Object>();
		// 调用验证码验证工具类,查询验证码是否正确
		if (!CodeUtil.checkVerifyCode(request)) {
			logger.error("用户验证码错误");
			modelMap.put("success", false);
			modelMap.put("errMsg", "验证码输入错误");
			return modelMap;
		}

		// 1、接受并转化相应的参数，包括店铺信息以及图片信息
		String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
		// 1.1转换成json数据，先创建一个ObjectMapper
		ObjectMapper mapper = new ObjectMapper();
		// 定义一个pojo去接收，可以看github json文档
		Shop shop = null;
		try {
			logger.debug("转换JSON数据为shop对象");
			shop = mapper.readValue(shopStr, Shop.class);
		} catch (Exception e) {
			logger.error("JSON数据转换失败");
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
			return modelMap;
		}
		// 解析处理上传图片
		CommonsMultipartFile shopImg = null;
		// 参数意思为:从本次会话中获取上下文相关的内容
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (commonsMultipartResolver.isMultipart(request)) {
			// 强制转换，可以从multipartHttpResolverRequest获取文件流
			MultipartHttpServletRequest multipartHttpResolverRequest = (MultipartHttpServletRequest) request;
			// shopImg为前段定义的id
			shopImg = (CommonsMultipartFile) multipartHttpResolverRequest.getFile("shopImg");
		}
		// 2、修改店铺信息
		if (shop != null && shop.getShopId() != null) {
			// 直接调用Service层的时候，传入shopImg.getInputStream
			ShopExecution se;
			try {
				// 判断是否要修改图片，如果要不修改图片，直接只修改商铺信息
				if (shopImg == null) {
					logger.debug("用户没有上传图片信息，无需更改");
					se = shopService.modifyShop(shop, null);

				} else {
					//重构 将图片流与图片名称合二为一
					ImageHolder imageHolder = new ImageHolder(shopImg.getOriginalFilename(),shopImg.getInputStream());
					logger.debug("用户上传了图片信息，需要更改");
					se = shopService.modifyShop(shop, imageHolder);

				}
				if (se.getState() == ShopStateEnum.SUCCESS.getState()) {
					logger.debug("用户更新成功");
					modelMap.put("success", true);
				} else {
					logger.error("用户更新失败");
					modelMap.put("success", false);
					modelMap.put("errMsg", se.getStateInfo());
				}
			} catch (ShopOperationException e) {
				logger.error("店铺操作失败");
				modelMap.put("success", false);
				modelMap.put("errMsg", e.getMessage());
			} catch (IOException e) {
				logger.error("用户上传图片解析失败");
				modelMap.put("success", false);
				modelMap.put("errMsg", e.getMessage());
			}
			// 如果创建成果，即是待审核状态

			return modelMap;
		} else {
			logger.error("没有对应的商铺Id");
			modelMap.put("success", false);
			modelMap.put("errMsg", "请输入店铺id");
			return modelMap;
		}
		// 3、返回结果

	}
	// 因为CommonsMultipartFile对象无法直接强制转换为File,所以要绕过InputStreamTofile
	// 因为可能会产生文件找不到等错误，直接传入inputStream，重构代码
	/*
	 * private static void inputStreamToFile(InputStream ins,File file){
	 * FileOutputStream os = null; try{ os = new FileOutputStream(file); int
	 * bytesRead =0; byte[] buffer = new byte[1024]; while((bytesRead
	 * =ins.read(buffer))!=-1 ){ os.write(buffer, 0, bytesRead); }
	 * }catch(Exception e){ throw new
	 * RuntimeException("调用inputStrem ToFile产生异常"+e.getMessage()); }finally{
	 * try{ if(os!=null){ os.close(); } if(ins!=null){ ins.close(); }
	 * }catch(IOException e){ throw new
	 * RuntimeException("关闭IO流的时候产生异常"+e.getMessage());
	 * 
	 * } } }
	 */
}
